<template>
  <view class="profile-edit-page">
    <!-- 表单区 -->
    <view class="profile-card">
      <van-cell-group>
        <!-- 头像单独渲染 -->
        <view @click="chooseAvatar">
          <van-field
            label="头像"
            is-link
            readonly
            clickable
            autoSize
            custom-class="profile-avatar-field"
          >
            <template #input>
              <image
                :src="formatImgUrl(form.avatar)"
                class="profile-avatar"
              />
            </template>
          </van-field>
        </view>
        <!-- 统一渲染其他字段 -->
        <block v-if="Array.isArray(fields)">
          <block
            v-for="(field, index) in fields"
            :key="index"
          >
            <van-field
              :key="index"
              :label="field.label"
              :value="form[field.key] || ''"
              :placeholder="field.placeholder"
              type="text"
              :is-link="field.isLink || false"
              :readonly="field.readonly || false"
              :clickable="field.clickable || false"
              :border="true"
              @clickInput="handleFieldClick(field)"
              @change="(val) => inputChange(val, form, field.key)"
            >
              <template
                v-if="field.key === 'enterpriseAddress'"
                #right-icon
              >
                <van-icon
                  name="replay"
                  size="18"
                  color="#0C8D6A"
                  @click.stop="refreshAddress"
                />
              </template>
            </van-field>
            <!-- 在第三个字段后显示分隔条 -->
            <view
              v-if="index === 2"
              class="profile-divider"
            ></view>
          </block>
        </block>
      </van-cell-group>
    </view>

    <!-- 介绍区 -->
    <view class="profile-intro-wrap">
      <view class="profile-intro-label-row">
        <text class="profile-intro-label">介绍</text>
        <text class="profile-intro-count">
          <text :style="{ color: introNumber > 100 ? '#f44' : '#888' }">{{
            introNumber
          }}</text>
          /100
        </text>
      </view>
      <van-field
        :value="form.introduce"
        type="textarea"
        placeholder="请输入介绍"
        autosize
        :border="false"
        custom-style="background: #f4f4f4;borderRadius: 8px"
        @change="onIntroChange"
      />
    </view>

    <!-- 性别选择器 -->
    <van-popup
      :show="showGenderPicker"
      position="bottom"
      @close="showGenderPicker = false"
    >
      <van-picker
        show-toolbar
        :columns="genderOptions"
        @confirm="onGenderConfirm"
        @cancel="showGenderPicker = false"
      />
    </van-popup>
    <!-- 出生年月选择器 -->
    <van-popup
      :show="showBirthPicker"
      position="bottom"
      @close="showBirthPicker = false"
    >
      <van-datetime-picker
        type="date"
        :value="currentDate"
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="onBirthConfirm"
        @cancel="showBirthPicker = false"
      />
    </van-popup>

    <!-- 底部操作栏 -->
    <view class="footer-bar">
      <van-button
        class="footer-btn cancel"
        type="default"
        block
        round
        @click="cancel"
        >取消</van-button
      >
      <van-button
        class="footer-btn save"
        type="primary"
        color="#0C8D6A"
        block
        round
        @click="save"
        >保存</van-button
      >
    </view>
  </view>
</template>

<script>
  import { getUserByOpenId, updateUserInfo } from '../../api/personal.js'
  import operate from '../../common/operate.js'
  import { formatImgUrl } from '../../common/utils.js'

  export default {
    data() {
      return {
        form: {
          userId: '',
          deptId: '',
          userName: '',
          nickName: '',
          email: '',
          phonenumber: '',
          sex: '',
          avatar: '',
          password: '',
          status: '',
          delFlag: '',
          loginIp: '',
          loginDate: '',
          dept: null,
          roles: null,
          roleIds: null,
          postIds: null,
          roleId: '',
          openId: '',
          userType: '',
          dateBirth: '',
          enterpriseName: '',
          personCharge: '',
          enterpriseAddress: '',
          introduce: '',
          sexText: ''
        },
        introNumber: 0,
        showGenderPicker: false,
        showBirthPicker: false,
        genderOptions: ['男', '女'],
        minDate: new Date(1950, 1, 1).getTime(),
        maxDate: new Date().getTime(),
        currentDate: new Date().getTime(),
        fields: [
          { label: '姓名', key: 'nickName', placeholder: '请输入' },
          {
            label: '性别',
            key: 'sexText',
            placeholder: '请选择',
            isLink: true,
            readonly: true,
            clickable: true
          },
          {
            label: '出生年月',
            key: 'dateBirth',
            placeholder: '请选择',
            isLink: true,
            readonly: true,
            clickable: true
          },

          {
            label: '企业名称',
            key: 'enterpriseName',
            placeholder: '请输入'
          },
          {
            label: '负责人',
            key: 'personCharge',
            placeholder: '请输入'
          },
          {
            label: '联系电话',
            key: 'phonenumber',
            placeholder: '请输入'
          },
          {
            label: '企业地址',
            key: 'enterpriseAddress',
            placeholder: '请输入'
          }
        ],
        columns: ['杭州', '宁波', '温州', '嘉兴', '湖州']
      }
    },
    onLoad() {
      this.loadUserInfo()
    },
    methods: {
      formatImgUrl,
      async loadUserInfo(setStorage = false) {
        const user = uni.getStorageSync('user')
        const openId = user.openId
        try {
          const res = await getUserByOpenId({ openId })
          if (res.code === 200 && res.data) {
            const d = res.data
            this.form = d
            this.form.sexText = d.sex === '0' ? '男' : d.sex === '1' ? '女' : ''
            this.introNumber = this.form.introduce?.length || 0
            if (setStorage) {
              uni.setStorageSync('user', d)
              uni.redirectTo({
                url: '/pagesA/my/index'
              })
            }
          }
        } catch (e) {
          uni.showToast({ title: '获取用户信息失败', icon: 'none' })
        }
      },
      inputChange(val, obj, key) {
        obj[key] = val?.detail || ''
      },
      chooseAvatar() {
        uni.chooseImage({
          count: 1,
          success: async (res) => {
            console.log('res: ', res)
            if (res.tempFilePaths && res.tempFilePaths[0]) {
              const filePath = res.tempFilePaths[0]
              try {
                const token = uni.getStorageSync('token')
                const url = operate.api() + '/common/upload'
                console.log('url: ', url)
                const Authorization = 'Bearer ' + token
                const uploadRes = await new Promise((resolve, reject) => {
                  uni.uploadFile({
                    url,
                    filePath,
                    name: 'file',
                    header: {
                      Authorization,
                      'Content-Type': 'multipart/form-data'
                    },
                    success: (uploadFileRes) => {
                      let data = uploadFileRes.data
                      if (typeof data === 'string') {
                        data = JSON.parse(data)
                      }
                      if (data.code === 200 && data.fileName) {
                        resolve(data)
                      } else {
                        reject(data.msg || '上传失败')
                      }
                    },
                    fail: (err) => reject(err)
                  })
                })
                this.form.avatar = uploadRes.fileName
              } catch (e) {
                console.log('e: ', e)
                uni.showToast({ title: '头像上传失败', icon: 'none' })
              }
            }
          }
        })
      },
      onGenderConfirm(val) {
        console.log('val: ', val)
        this.form.sex = val.detail.index
        this.form.sexText = val.detail.value
        this.showGenderPicker = false
      },
      onBirthConfirm(val) {
        // detail: 1749229566499
        const date = new Date(val.detail)
        this.form.dateBirth =
          date.getFullYear() +
          '-' +
          (date.getMonth() + 1) +
          '-' +
          date.getDate()
        this.showBirthPicker = false
      },
      refreshAddress() {
        // TODO: 地址刷新逻辑
        uni.showToast({ title: '地址已刷新', icon: 'success' })
      },
      async save() {
        try {
          await updateUserInfo(this.form)
          uni.showToast({ title: '保存成功', icon: 'success' })
          await this.loadUserInfo(true)
        } catch (e) {
          console.log('e: ', e)
        }
      },
      cancel() {
        uni.navigateBack()
      },
      handleFieldClick(field) {
        console.log('handleFieldClick: ', field)
        if (field.key === 'sexText') {
          this.showGenderPicker = true
        } else if (field.key === 'dateBirth') {
          this.showBirthPicker = true
        }
      },
      onIntroChange(val) {
        this.form.introduce = val.detail
        this.introNumber = this.form.introduce.length
      }
    }
  }
</script>

<style lang="scss">
  .profile-edit-page {
    background: #f5f6fa;
    min-height: 100vh;
    padding-top: 0rpx;
  }
  .profile-title {
    color: #222;
    font-size: 20px;
    font-weight: bold;
  }
  .profile-card {
    background: #fff;
    box-shadow: 0 4rpx 24rpx 0 rgba(0, 0, 0, 0.04);
    overflow: hidden;
  }
  .profile-label {
    width: 180rpx;
    color: #888;
    font-size: 28rpx;
  }
  .profile-label-avatar {
    width: 240rpx;
  }
  .profile-input {
    font-size: 28rpx;
    color: #222;
  }
  .profile-placeholder {
    color: #ccc;
  }
  .profile-avatar-field {
    height: 80px !important;
    display: flex !important;
    align-items: center !important;
    .van-cell__value {
      height: 80px !important;
      display: flex !important;
      align-items: center !important;
    }
  }
  .profile-avatar {
    width: 80rpx;
    height: 80rpx;
    border-radius: 50%;
    margin-right: 0;
  }
  .profile-divider {
    height: 16rpx;
    background: #f5f6fa;
    margin: 0;
    width: 100%;
    position: relative;
    left: 0;
    right: 0;
  }
  .profile-intro-wrap {
    background: #fff;
    margin-top: 16rpx;
    padding: 24rpx;
  }
  .profile-intro-label-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12rpx;
  }
  .profile-intro-label {
    color: #646566;
    font-size: 28rpx;
  }
  .profile-intro-count {
    color: #888;
    font-size: 24rpx;
  }
  .profile-intro-field {
    background: #f7f8fa;
    border-radius: 8rpx;
    padding: 12rpx 16rpx;
    min-height: 120rpx;
    margin-bottom: 12rpx;
  }
  .profile-intro-input {
    font-size: 28rpx;
    color: #222;
  }
  .profile-intro-tip {
    color: #888;
    font-size: 26rpx;
    background: #f7f8fa;
    border-radius: 8rpx;
    padding: 16rpx;
  }
  .footer-bar {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    background: #fff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 24rpx 32rpx 48rpx 32rpx;
    z-index: 10;
    box-shadow: 0px 7px 46px 0px rgba(0, 0, 0, 0.33);
  }
  .footer-btn {
    flex: 1;
    height: 88rpx;
    font-size: 32rpx;
    border-radius: 44rpx;
    margin: 0 12rpx;
  }
  .footer-btn.cancel {
    background: #fff;
    color: #222;
    box-shadow: 0 2rpx 8rpx 0 rgba(19, 174, 124, 0.04);
  }
  .footer-btn.save {
    background: #0c8d6a;
    color: #fff;
  }
</style>
